/*
 * @Author: Binhuang4
 * @Date: 2019-06-04 17:13:49
 * @LastEditors: Binhuang4
 * @LastEditTime: 2019-06-06 10:51:49
 * @Description: Definition for singly-linked list.
 */
package main

import (
	"encoding/json"
	"fmt"
)

type ListNode struct {
	Val  int
	Next *ListNode
}

func main() {
	l1 := &ListNode{5, &ListNode{6, &ListNode{7, nil}}}
	l2 := &ListNode{8, &ListNode{2, &ListNode{1, nil}}}
	//l2 := &ListNode{8, &ListNode{2, &ListNode{1, &ListNode{1, nil}}}}
	ln := addTwoNumbers(l1, l2)
	fmt.Println(toJson(ln))
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
	i := 1
	var sum1 int
	var sum2 int
	for {
		if l1 != nil {
			sum1 = sum1 + l1.Val*i
		}
		if l2 != nil {
			sum2 = sum2 + l2.Val*i
		}
		i = i * 10
		if l2 != nil {
			l2 = l2.Next
		}
		if l1 != nil {
			l1 = l1.Next
		}
		if l1 == nil && l2 == nil {
			break
		}
	}
	sum := sum1 + sum2
	var mod = sum % 10
	var ln = &ListNode{mod, nil}
	tmpLN := &ListNode{0, nil}
	//893   3 -> 9 -> 8

	for {

	}
	for {
		tmpLN = ln
		sum = (sum - mod) / 10
		mod = sum % 10
		ln = &ListNode{mod, nil}
		ln.Next = tmpLN
		if sum < 10 {
			break
		}
	}
	return ln
}

func addNextNode(ln *ListNode, sum int, mod int) *ListNode {
	if mod != 0 {
		addNextNode(ln, sum, mod)
	} else {
		sum = (sum - mod) / 10
		mod = sum % 10
		tmpLN := &ListNode{mod, nil}
		ln.Next = tmpLN
	}
	return ln
}

func toJson(i interface{}) string {
	jsonBytes, _ := json.Marshal(i)
	return string(jsonBytes)
}
func addTwoNumbers1(l1 *ListNode, l2 *ListNode) *ListNode {
	head := &ListNode{0, nil}
	p, q, curr := l1, l2, head
	jinwei := 0
	for p != nil || q != nil {
		x := 0
		y := 0
		if p != nil {
			x = p.Val
		}
		if q != nil {
			y = q.Val
		}
		addRs := x + y + jinwei
		curr.Next = &ListNode{addRs % 10, nil}
		curr = curr.Next
		if p != nil {
			p = p.Next
		} else {
			p = nil
		}
		if q != nil {
			q = q.Next
		} else {
			q = nil
		}
		if addRs >= 10 {
			jinwei = 1
		} else {
			jinwei = 0
		}
	}
	if jinwei == 1 {
		curr.Next = &ListNode{1, nil}
	}
	return head.Next
}
